<script setup name="home">
import Header from '@/views/Layout/Header/Header.vue'
import Menu from '@/views/Layout/Menu/Menu.vue'
import PostDetail from '@/views/PostDetail/PostDetail.vue'
import { useRoute } from 'vue-router'
import Login from '../Login/Login.vue'
import { useHeaderStore } from '../Layout/Header/stores/headerStore'
import { useGlobalStore } from '@/stores/globalStore'
import PostDetailGallery from '../PostDetail/PostDetailGallery.vue'
import UserInfoEdit from '@/components/UserInfoEdit/UserInfoEdit.vue'
import FormItemEdit from '@/components/FormItemEdit.vue'
import { useTopicManageStore } from '@/stores/TopicManageStore'
// import { recordVisitor } from '@/axios/api/user'
import { computed, watch, onMounted, onUnmounted, ref, getCurrentInstance } from 'vue'
import ChatPanel from '@/components/chat/ChatPanel.vue'
import websocket from '@/utils/websocket'

const headerStore = useHeaderStore()
const topicManageStore = useTopicManageStore()
const globalStore = useGlobalStore()

const route = useRoute()

// const isPostDetailShow = ref(false)
const isUserCenterShow = ref(false)

const mainAreaRef = ref(null)

const storageWidth = localStorage.getItem('detailPanelWidth')

const rightWidth = ref(storageWidth ? storageWidth : 700) // 初始左右侧宽度
const minRightWidth = 500 // 最小宽度
const maxRightWidth = window.innerWidth - 600 // 最大宽度

const currentRoutePath = ref('')

let isDragging = false

const showChatPanel = ref(false)

// 开始拖动
const startDragging = () => {
  isDragging = true
}

// 更新宽度
const handleDragging = (e) => {
  if (isDragging) {
    const mouseX = e.clientX // 鼠标到屏幕左侧的距离
    const screenWidth = window.innerWidth // 屏幕的宽度
    let distanceToRight = screenWidth - mouseX // 鼠标到右侧屏幕的距离

    // 限制宽度范围
    if (distanceToRight < minRightWidth) {
      distanceToRight = minRightWidth
    } else if (distanceToRight > maxRightWidth) {
      distanceToRight = maxRightWidth
    }

    rightWidth.value = distanceToRight

    localStorage.setItem('detailPanelWidth', distanceToRight)

    // 根据宽度判断是否显示菜单
    if (mainAreaRef.value.clientWidth >= 700) {
      globalStore.setIsMenuShow(true)
      globalStore.setIsMenuAbsShow(false)
    } else {
      globalStore.setIsMenuShow(false)
    }
  }
}

// 停止拖动
const stopDragging = () => {
  isDragging = false
}

const isPostDetailRoute = computed(() => {
  // 只在路径包含 /post/ 且 params.id 存在时才为帖子详情
  return route.path.includes('/post/') && !!route.params.id
})

onMounted(async () => {
  // 记录访客统计
  // recordVisitor({ terminal: 'pc' }).catch((error) => {
  //   console.error('Failed to record visitor:', error)
  // })

  window.addEventListener('mousemove', handleDragging)
  window.addEventListener('mouseup', stopDragging)

  if (localStorage.getItem('postDetailMode')) {
    globalStore.setPostDetailMode(localStorage.getItem('postDetailMode'))
  }

  if (
    isPostDetailRoute.value &&
    (globalStore.postDetailMode === 'split screen' || globalStore.viewMode === 'gallery')
  ) {
    globalStore.setPostDetailShow(true)
  } else {
    globalStore.setPostDetailShow(false)
  }

  if (route.params.uid) {
    isUserCenterShow.value = true
  }

  const observer = new MutationObserver(() => {
    if (mainAreaRef.value.clientWidth < 700) {
      globalStore.setIsMenuShow(false)
    } else {
      globalStore.setIsMenuShow(true)
    }
  })

  observer.observe(mainAreaRef.value, {
    attributes: true,
    childList: true,
    subtree: true,
  })

  // 提供全局方法供其他组件调用
  if (typeof window !== 'undefined') {
    window.$openChatPanel = () => { showChatPanel.value = true }
    window.$closeChatPanel = () => { showChatPanel.value = false }
  }
})

onUnmounted(() => {
  window.removeEventListener('mousemove', handleDragging)
  window.removeEventListener('mouseup', stopDragging)
})

// 监听路由变化
watch(route, (newRoute, oldRoute) => {
  globalStore.setIsMenuAbsShow(false)

  // 根据宽度判断是否显示菜单
  if (mainAreaRef.value.clientWidth >= 700) {
    globalStore.setIsMenuShow(true)
    globalStore.setIsMenuAbsShow(false)
  } else {
    globalStore.setIsMenuShow(false)
  }

  currentRoutePath.value = newRoute.path

  if (
    isPostDetailRoute.value &&
    (globalStore.postDetailMode === 'split screen' || globalStore.viewMode === 'gallery')
  ) {
    globalStore.setPostDetailShow(true)
  } else {
    globalStore.setPostDetailShow(false)
  }
})

function handleLoginSuccess() {
  websocket.initConnect()
}
</script>

<template>
  <div :class="globalStore.isPostDetailShow ? 'flex' : ''" class="bg-[--surface-1] h-full">
    <UserInfoEdit v-if="headerStore.isShowUserInfoEdit" />
    <FormItemEdit v-if="topicManageStore.isShowTopicSetting" />

    <Login @login-success="handleLoginSuccess" />

    <ChatPanel v-if="showChatPanel" style="position: fixed; bottom: 32px; right: 32px; z-index: 9999;" />

    <div
      class="flex flex-col h-screen rounded-tr-lg rounded-br-lg overflow-hidden flex-1 bg-[--surface-0]"
      ref="mainAreaRef">
      <Header :isShowMenu="globalStore.isMenuShow" />

      <div class="flex flex-grow overflow-hidden relative">
        <Menu v-if="globalStore.isMenuShow || globalStore.isMenuAbsShow" :route="currentRoutePath" />
        <!-- style=" margin: 0px 3%;" -->
        <main class="overflow-y-auto h-full flex-grow " >
          <RouterView />
        </main>
      </div>

      <!-- 添加备案信息 -->
      <!-- <footer class="text-center py-2 text-sm text-gray-500">
        <a
          href="https://beian.miit.gov.cn/"
          target="_blank"
          rel="noopener noreferrer"
          class="text-gray-500 hover:text-gray-700">
          CopyRight © 2022-2025
        </a>
      </footer> -->
    </div>

    <!-- <div
      v-if="globalStore.isPostDetailShow"
      id="divider"
      @mousedown="startDragging"
      class="w-2 bg-[--surface-1] cursor-ew-resize"></div> -->

    <!-- <PostDetail
      v-if="globalStore.isPostDetailShow && globalStore.viewMode === 'list'"
      :style="{ width: globalStore.isPostDetailShow ? rightWidth + 'px' : '100%' }" /> -->
    <!-- <PostDetailGallery
      :visible="globalStore.isPostDetailShow"
      v-if="globalStore.isPostDetailShow && globalStore.viewMode === 'gallery'" /> -->
  </div>
</template>

<style scoped lang="scss"></style>
